<template>
   <div class="channelNews-container">
       <div class="type-title">{{ channelName }}</div>
       <NewsList :newsList="newsList"/>
       <Loading/>
   </div>
</template>

<script>
import PubSub from 'pubsub-js';

import NewsList from './news/NewsList';
import Loading from './Loading';
import { getNewsList } from '../services/NewsService';

export default {
    components: {
        NewsList,
        Loading
    },
    data() {
        return {
            newsList: [],
            pageSize: 10,
            isLoading: true,
            token: null
        }
    },
    computed: {
        page: {
            get() {
                return parseInt(this.$route.params.page) || 1;
            },
            set(page) {
                this.$route.params.page = page;
            }
        },
        channelName() {
            let channels = this.$store.state.channels.data;
            if (channels.length > 0) {
                let channel = channels.find((item) => item.action === this.$route.params.action);
                return channel.name || '';
            }
            return '';
        }
    },
    methods: {
        handleChange(newPage) {
            this.$router.push({
                name: 'ChannelNews',
                params: {
                    id: this.$route.params.id,
                    page: newPage
                }
            });
            this.setNews();
        },
        async setNews() {
            this.isLoading = true;
            let { newsList } = await getNewsList(this.$route.params.action, this.page, this.limit);
            this.newsList = newsList;
            this.isLoading = false;
        },
        loadMore() {
            if (this.isLoading) return;
            this.isLoading = true;
            getNewsList(this.$route.params.action, this.page + 1, this.pageSize)
            .then(data => {
                data.newsList.forEach(item => this.newsList.push(item));
                this.page = data.page;
                this.isLoading = false;
            }).catch(() => this.isLoading = false);
        }
    },
    watch: {    //监控数据的变化，当数据变化时，要做一些事
        '$route.params.action': {
            immediate: true,  //一开始的数据也要当作是一种变化
            handler() {
                this.setNews();
                document.title = this.channelName;
            }
        }
    },
    created() {
        // 订阅页面滚动到底部的消息
        this.token = PubSub.subscribe('scrollBottom', () => {
            this.loadMore();
        });
    },
    destroyed() {
        PubSub.unsubscribe(this.token);
        this.token = null;
    }
}
</script>

<style scoped>
.channelNews-container {
    width: 1140px;
    margin: 60px auto;
}
.type-title {
    font-size: 2em;
    color: #888;
    border-bottom: 1px solid #ccc;
    padding-bottom: 10px;
}
</style>